$(function() {

    let id = location.search.split('=')[1]
        //如果有id，则为编辑，需要填充数据

    if (id) {
        setTimeout(() => {
            $.ajax({
                url: bigNews.article_search,
                headers: { 'Authorization': localStorage.getItem('bigNews_token') },
                data: { id },
                dataType: 'json',
                success: function(res) {
                    $('#inputTitle').val(res.data.title)
                    $('.article_cover').attr('src', res.data.cover)
                    $('.category').val(res.data.categoryId)
                    $('#postDate').val(res.data.date)
                    $('#mytextarea').html(res.data.content)

                    //如果使用富文本框的方法，则需要添加延时器，因为比较大，加载比较慢，要先等结构加载完才能设置内容
                    // setTimeout(() => {
                    //     tinyMCE.activeEditor.setContent(res.data.content)
                    // }, 300);
                }
            }, 50);

        })
    }


    //发布时间
    jeDate("#postDate", {
        isinitVal: true,
        maxDate: new Date().toLocaleDateString(),
        theme: { bgcolor: "pink", color: "#ffffff", pnColor: "skyblue" },
        format: 'YYYY-MM-DD'
    });

    //富文本框初始化
    tinymce.init({
        selector: '#mytextarea',
        height: '350px',
        language: 'zh_CN',
        directionality: 'ltl',
        browser_spellcheck: true,
        contextmenu: false,
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste imagetools wordcount",
            "code"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code",
    });

    //动态渲染文章分类
    $.ajax({
        url: bigNews.category_list,
        headers: { 'Authorization': localStorage.getItem('bigNews_token') },
        dataType: 'json',
        success: function(res) {
            // console.log(res);
            $('.category').html(template('optTem', res))
        }
    })

    //渲染封面
    $('#inputCover').on('change', function() {
        let myfile = $('#inputCover')[0].files[0]
        if (myfile.type.indexOf('image/') == -1) {
            alert('请选择图片文件')
            return
        }
        //通过URL顶级内置对象的createObjectURL方法获取本地文件的url
        let url = URL.createObjectURL(myfile)
        $('.article_cover').attr('src', url)
    })


    function publishPost(state) {

        let formdata = new FormData()

        //标题
        let title = $('#inputTitle').val()
            // console.log(title)
        if (title.trim().length === 0) {
            alert('请输入标题')
            return
        }

        //封面
        let myfile = $('#inputCover')[0].files[0]
            // console.log(myfile);

        if (!id) {
            if (!myfile) {
                alert('请选择封面')
                return
            }
            if (myfile.type.indexOf('image/') == -1) {
                alert('请选择图片文件')
                return
            }
            formdata.append('cover', myfile)
        } else {
            formdata.append('id', id)
            if (myfile && myfile.type.indexOf('image/') === -1) {
                alert('请选择图片文件')
                return
            } else if (myfile && myfile.type.indexOf('image/') !== -1) {
                formdata.append('cover', myfile)
            }
        }

        //获取分类id
        let cateId = $('.category').val() - 0

        //获取日期内容
        let date = $('#postDate').val()


        //获取富文本框内容
        let content = tinyMCE.activeEditor.getContent()
        if (content.length === 0) {
            alert('请输入文章内容')
            return
        }
        // console.log(content);

        formdata.append('title', title)
        formdata.append('categoryId', cateId)
        formdata.append('date', date)
        formdata.append('content', content)
        formdata.append('state', state)

        $.ajax({
            type: 'post',
            url: id ? bigNews.article_edit : bigNews.article_publish,
            headers: { 'Authorization': localStorage.getItem('bigNews_token') },
            data: formdata,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function(res) {
                alert(res.msg)
                location.assign('./article_list.html')
                    // location.href = './article_list.html'
            }
        })

    }
    //发布文章
    $('.btn-release').on('click', function(e) {
            e.preventDefault()
            let state = '已发布'
            publishPost(state)
        })
        //存为草稿
    $('.btn-draft').on('click', function(e) {
        e.preventDefault()
        let state = '草稿'
        publishPost(state)
    })

})